<template>
  <div v-if="SongDetail">
    <!-- 全屏播放器 -->
    <div class="player" v-show="showPlayer">
      <div
        class="bg"
        :style="'background-image: url(' + SongDetail.al.picUrl + ')'"
      ></div>
      <div class="shade"></div>
      <div class="view">
        <div class="button" @click.stop="showPlayer = false">
          <span class="iconfont icon-arrow-down-bold"></span>
        </div>
        <div class="title">
          <h2>{{ SongDetail.name }}</h2>
          <h3>
            <span v-for="(item, index) in SongDetail.ar" :key="index" @click="getSinger(item.id)"
              >{{ item.name }}&nbsp;</span
            >
          </h3>
        </div>
        <div class="content">
          <div
            v-show="togglelyric"
            @click="togglelyric = false"
            :class="['img', 'play', { pause: iconplay }]"
          >
            <img :src="SongDetail.al.picUrl" alt="" />
          </div>
          <div class="lyrics" v-show="!togglelyric" @click="togglelyric = true">
            <ul :style="{ top: lyricTop }">
              <li
                v-for="(item, index) in lyric"
                :key="index"
                :class="{ con: currentRow == index }"
              >
                {{ item.text }}
              </li>
            </ul>
          </div>
          <div class="lits">
            <span class="iconfont icon-shoucang" @click="love=2" v-show="love==1"></span>
            <span @click="love=1" v-show="love==2"><van-icon name="like" size="24"/></span>
            <span   class="iconfont icon-pinglun-" @click="goComment"></span>
            <span class="iconfont icon-tianjia" @click="shouCang=!shouCang"></span>
          </div>
        </div>
        <div class="range">
          <div class="bar">
            <span class="timeLeft">{{ timeLeft | playerTime }}</span>
            <van-slider
              @change="sliderchange"
              v-model="value"
              inactive-color="#514E4C"
              bar-height="4px"
              active-color="#ee0a24"
            >
              <template #button>
                <div class="custom-button"></div>
              </template>
            </van-slider>
            <span class="timeRight">{{ timeRight | playerTime }}</span>
          </div>
        </div>
        <div class="buttons">
          <div
            :class="[
              'iconfont',
              { 'icon-xunhuanbofang': playFlg == 1 },
              { 'icon-suijibofang': playFlg == 2 },
            ]"
            @click="playFlgFun"
          ></div>
          <div
            class="iconfont icon-shangyiqu-wangyiicon"
            @click="startup"
          ></div>
          <div
            :class="['iconfont', iconplay ? 'icon-bofang' : 'icon-zantingtingzhi']"
            @click.stop="toggleplay"
          ></div>
          <div class="iconfont icon-shangyiqu" @click="lowerFun"></div>
          <div class="iconfont">
            <van-icon name="bars" @click="show = !show" />
          </div>
        </div>
      </div>
    </div>
    <!-- 收藏列表 -->
    <van-dialog v-model="shouCang" title="标题">
        <shouchang :player-id="playerId"></shouchang>
    </van-dialog>
    <!-- 迷你播放器 -->
    <div class="mini-player" v-if="SongDetail" @click="showPlayer = true">
      <div :class="['img', 'play', { pause: iconplay }]">
        <img :src="SongDetail.al.picUrl" alt="" />
      </div>
      <div class="text">
        <h2>{{ SongDetail.name }}</h2>
        <h3>
          <span v-for="(item, index) in SongDetail.ar" :key="index"
            >{{ item.name }}&nbsp;</span
          >
        </h3>
      </div>
      <div class="control" @click.stop="toggleplay">
        <span class="iconfont icon-bofang" v-show="iconplay"></span>
        <span class="iconfont icon-zantingtingzhi" v-show="!iconplay"></span>
        
      </div>
       <div class="iconfont" style="margin: 11px 14px 0 0;font-size: 30px;">
            <van-icon name="bars" @click.stop="show = !show" />
          </div>
    </div>
    <!-- oncanplay	当媒介能够开始播放但可能因缓冲而需要停止时运行脚本 -->
    <!-- loadeddata 	当加载媒介数据时运行脚本 -->
    <!-- 音频播放器 -->
    <audio
      ref="audio"
      hidden
      controls
      :src="musicData"
      @loadeddata="loadeddataFun"
      @ended="endedFun"
    ></audio>
    <!-- //迷你列表 -->
    <van-popup
      v-model="show"
      round
      position="bottom"
      :style="{ height: '40%' }"
    >
      <div class="minList">
        <div class="nav">
          <h2>当前播放({{ minList.length }})</h2>
        </div>
        <div class="btn">
          <div class="left">
            <i class="iconfont" :class="iconMode" @click="changeMode"></i>
            <span class="text">{{ modeText }}
              (<span class="count">{{minList.length}}</span>)
            </span>
          </div>
          <div class="right">
            <van-icon name="delete-o" @click="delList"/>
          </div>
        </div>
        <ul>
          <li v-for="(item, index) in minList" :key="item.id+'1'"  @click="setId(item.id)">
            <div class="left">
              <van-icon :name="getCurrentIcon(item)" color="red"/><span>{{ item.name }}</span
              > - <span>{{ item.ar[0].name }}</span>
            </div>
            <div class="right">
              <van-icon name="cross" @click="minDel(index)" color="red"/>
            </div>
          </li>
        </ul>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { Toast } from 'vant';
import { getSongUrl, getSongDetail, getLyric } from "../api/base";
import { getPlaylistDetail } from "../api/rank";
import {likeMusic,getLikeList} from "../api/user"
import shouchang from "./shouchang.vue";
export default {
  components: { shouchang },
  props: ["playerId", "listId"],
  data() {
    return {
      show: false,
      musicData: "",
      iconplay: true, //播放按钮
      SongDetail: null, //歌曲信息
      value: 0, //滚动条 0-100
      showPlayer: false, //全屏播放器状态
      timeRight: 0, //右侧时间
      timeLeft: 0, //左侧时间
      clearset: null, //定时器
      playerLists: [], //播放列表
      togglelyric: false, //歌词切换
      lyric: [], //歌词数组
      lyricTop: "200px", //歌词位置
      currentRow: 0, //歌词高亮
      playFlg: 1, //播放模式
      minList: [], //迷你列表
      minId: [],
      shouCang: false, //收藏列表
      love:1,
      userDataList:null
    };
  },
  methods: {
    getSinger(id){
       this.$router.push({ path: "songGerItem", query: { id } });
    },
     getCurrentIcon (item) {
      if (this.playerId === item.id) {
        return 'bar-chart-o'
      }
      return ''
    },
    changeMode(){
      if(this.playFlg==1){
        this.playFlg=2
      }else{
        this.playFlg=1
      }
    },
    delList(){
        this.minList=[]
    },
    goComment(){
      this.$router.push({ path: "comment", query: { id:this.playerId} });
    },
    // 获取歌曲url
    setId(id) {
      this.$emit("get-player-id", id);
      //  this.$emit("get-play-all-id",this.$route.query.id);//传递歌单id
      console.log(id);
    },
    getSongUrlFun() {
      getSongUrl({ id: this.playerId }).then((data) => {
        this.musicData = data.data[0].url;
        this.iconplay = true;
      });
    },
    // 获取歌曲信息
    getSongDetailFun() {
      getSongDetail({ ids: this.playerId }).then((data) => {
        console.log(data);
        this.SongDetail = data.songs[0];
        console.log(this.SongDetail)
      });
    },
    // 获取歌曲歌词
    getLyricFun() {
      getLyric({ id: this.playerId }).then((data) => {
        console.log(data);
        this.formatLyric(data.lrc.lyric);
      });
    },
    // 处理歌词结构
    formatLyric(text) {
      this.lyric = [];
      let arr = text.split("\n"); //把原歌词切割成字符串
      let row = arr.length; //获取数组长度
      for (let i = 0; i < row; i++) {
        let temp_row = arr[i]; //[00:00.000] 作词 : MK王逸杰
        let temp_arr = temp_row.split("]"); //[00:00.000 , 作词 : MK王逸杰
        let lyrictext = temp_arr.pop(); //删除数组最后一个,返回值
        temp_arr.forEach((el) => {
          let obj = {};
          // [00:00.000 => [00,00.000]
          let time_arr = el.substr(1, el.length - 1).split(":");
          let s = time_arr[0] * 60 + Math.ceil(time_arr[1]); //把分钟变成秒
          obj.text = lyrictext;
          obj.time = s;
          if (lyrictext.length > 0) {
            this.lyric.push(obj); //每一行歌词处理后放入数组中
          }
        });
      }
    },
    // 播放暂停音乐
    toggleplay() {
      if (this.iconplay) {
        this.$refs.audio.play(); //播放音乐
        // if(this.playerId=='null'){
        //     clearInterval(this.clearset); //清除定时器
        // }
        clearInterval(this.clearset); //清除定时器
        this.clearset = setInterval(() => {
          let currentTime = this.$refs.audio.currentTime; //实时变化时间
          let duration = this.$refs.audio.duration; //总时间
          this.timeLeft = currentTime;
          // 计算滚动条值
          this.value = (currentTime / duration) * 100;
          if (this.value == 100) {
            clearInterval(this.clearset);
            this.$refs.audio.pause(); //暂停音乐
            this.iconplay = true;
          }
        }, 999);
      } else {
        this.$refs.audio.pause(); //暂停音乐
        clearInterval(this.clearset);
      }

      this.iconplay = !this.iconplay; //切换页面
    },
    // 音乐加载完成后,获取音乐数据
    loadeddataFun() {
      let duration = this.$refs.audio.duration;
      this.timeRight = duration;
      // this.iconplay=!this.iconplay
      this.toggleplay();
    },
    // 获取滚动条变化
    sliderchange() {
      var duration = (this.$refs.audio.duration * this.value) / 100;
      this.timeLeft = duration; //修改页面数据
      this.$refs.audio.currentTime = duration; //修改播放时间
    },
    // 下一首歌
    lowerFun() {
      let id = this.SongDetail.id; // 获取id
      if (id in this.minList) {
        console.log("有id");
      } else {
        this.minId.push(id);
      }
      console.log(this.playerLists);
      // 获取在播放歌曲列表中下标
      let index = this.playerLists.findIndex((item) => item.id == id);
      // 1.获取当前歌曲下标,下标加一,下一首歌.如果最后一首歌,重置为零回到第一首歌
      index = index + 1 > this.playerLists.length - 1 ? 0 : index + 1;
      // 返回父组件歌曲id
      this.$emit("set-player-id", this.playerLists[index].id); //修改父组件id值
    },
    // 上一首歌
    startup() {
      let id = this.SongDetail.id; // 获取id
      // 获取在播放歌曲列表中下标
      let index = this.playerLists.findIndex((item) => item.id == id);
      console.log(index)
      // 1.获取当前歌曲下标,下标减一,上一首歌.如果第一首歌,设置为最后一首歌
      index = index - 1 < 0 ? this.playerLists.length - 1 : index - 1;
      // 返回父组件歌曲id
      this.$emit("set-player-id", this.playerLists[index].id); //修改父组件id值
    },
    playFlgFun() {
      this.playFlg = ++this.playFlg > 2 ? 1 : 2;
    },

    //播放完歌曲根据播放顺序下一首
    endedFun() {
      console.log("音乐播放结束");
      this.iconplay = true;
      if (this.playFlg == 1) {
        this.lowerFun();
      } else {
        //随机播放
        //  let index = parseInt(Math.random() * this.playerLists.length);
        // this.$emit("set-player-id",this.playerLists[index].id);
        let index = parseInt(Math.random() * this.playerLists.length);
        this.$emit("set-player-id", this.playerLists[index].id);
        console.log("随机播放");
      }
    },
    //删除迷你列表歌曲
    minDel(id) {
      this.minList.splice(id, 1);
    },
  },
  // 侦听器,只要数据修改,重新执行
  watch: {
    // 侦听播放id
    playerId() {
      this.getSongUrlFun(); //歌曲url
      this.getSongDetailFun(); //歌曲信息
      this.getLyricFun(); //歌曲歌词
      
      //查询歌曲是否在喜欢列表
      let uid=window.localStorage.getItem('uid');
      // let id=this.playerId
      getLikeList({uid}).then(data=>{
        this.userDataList=data.ids
        console.log(this.userDataList)
      })
    },
    userDataList(){
      this.userDataList.forEach(item=>{
       if(item==this.playerId){
         this.love=2;
         return
       }
      })
    },
    // 侦听播放列表id
    listId() {
      console.log("歌单数据");
      getPlaylistDetail({ id: this.listId }).then((data) => {
        this.playerLists = data.playlist.tracks; //获取歌单数据
        this.minList=data.playlist.tracks;
        console.log(this.playerLists);
      });
    },
    // 左测歌时间变化
    timeLeft() {
      for (let i = 0; i < this.lyric.length; i++) {
        if (parseInt(this.timeLeft) <= this.lyric[i].time) {
          this.lyricTop = 200 - i * 36 + "px";
          this.currentRow = i; //歌词高亮
          break;
        }
      }
    },
    minId() {
      getSongDetail({ ids: this.playerId }).then((data) => {
        console.log(data);
        this.minList.push(data.songs[0]);
      });
    },
    love(){
      if(this.love==2){
        likeMusic({
          id:this.playerId,
          like:true 
        }).then(data=>{
          if(data.code==200){
           console.log(data)
          }
        })
      }else{
        likeMusic({
          id:this.playerId,
          like:false 
        }).then(data=>{
          if(data.code==200){
            Toast('取消收藏成功')
          }
        })
      }
    },
  },
  filters: {
    playerTime(data) {
      let m = parseInt(data / 60); //分钟
      let s = parseInt(data % 60); //秒
      if (m == 0 && s == 0) {
        return "0:00";
      } else {
        return m + ":" + (s < 10 ? "0" + s : s); // 01
      }
    },
  },
  computed:{
     modeText () {
      return this.playFlg === 1 ? '顺序播放' :   '随机播放' 
    },
    iconMode () {
      if (this.playFlg === 1) {
        return 'icon-xunhuanbofang'
      } else if (this.playFlg === 2) {
        return 'icon-suijibofang'
      } else {
        return ''
      }
    },
  },
  beforeRouteUpdate(from,to,next){
    if(to('/mv')){
      console.log('mvaa')
    }
    next()
  },
  created(){

  }
};
</script>

<style lang="less">
.player {
  position: fixed;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 1);
  color: #fff;
  z-index: 2;
  .bg {
    position: absolute;
    top: 0px;
    left: 0px;
    width: 100%;
    height: 100%;
    // background-image: url("https://p2.music.126.net/e5cvcdgeosDKTDrkTfZXnQ==/109951166155165682.jpg");
    background-size: 100%;
    background-repeat: no-repeat;
    background-position: 50%;
    transform: scale(1.8);
    transform-origin: center center;
    filter: blur(30px);
    opacity: 1;
    z-index: 2;
  }
  .shade {
    position: absolute;
    z-index: 3;
    left: 0px;
    bottom: 0px;
    height: 50%;
    width: 100%;
    background-image: linear-gradient(180deg, rgba(0, 0, 0, 0), #000);
  }
  .view {
    position: absolute;
    z-index: 4;
    left: 0px;
    bottom: 0px;
    height: 100%;
    width: 100%;
    background: rgba(0, 0, 0, 0.2);
    .button {
      font-size: 22px;
      position: absolute;
      left: 13px;
      top: 13px;
      font-weight: bold;
    }
    .title {
      text-align: center;
      margin-top: 15px;
      h2 {
        font-size: 20px;
      }
      h3 {
        font-size: 14px;
      }
    }
    .content {
      text-align: center;
      height: 65%;
      width: 100%;
      position: relative;
      padding-top: 15px;

      .img {
        position: absolute;
        top: 0px;
        left: 0px;
        right: 0px;
        bottom: 0px;
        margin: auto;
        width: 300px;
        height: 300px;
        border-radius: 50%;
        background: rgba(0, 0, 0, 0.3);
        img {
          margin: 0 auto;
          width: 274px;
          height: 274px;
          border-radius: 50%;
          padding-top: 13px;
        }

        &.play {
          animation: rotate 20s linear infinite;
        }
        &.pause {
          animation-play-state: paused;
        }
      }
      .lyrics {
        width: 100%;
        height: 95%;
        position: relative;
        overflow: hidden;
        ul {
          position: absolute;
          width: 100%;
          top: 180px;
          left: 0px;
          transition: all 0.5s linear;
          li {
            height: 36px;
            line-height: 36px;
            color: #cbcccc;
            font-size: 16px;
            overflow: hidden;
            &.con {
              color: #fff;
            }
          }
        }
      }
      .lits{
        position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
        span{
          margin: 0 15px;
          font-size: 24px;
        }
      }

    }
  }
  .range {
    position: absolute;
    width: 100%;
    left: 0px;
    bottom: 110px;
    text-align: center;
    .bar {
      width: 66%;
      margin: auto;
      position: relative;
      font-size: 14px;
      .timeLeft {
        position: absolute;
        left: -34px;
        top: -6px;
      }
      .timeRight {
        position: absolute;
        right: -34px;
        top: -6px;
      }
    }
  }
  .buttons {
    display: flex;
    position: absolute;
    bottom: 40px;
    width: 100%;
    .iconfont {
      flex: 1;
      width: 20%;
      text-align: center;
      font-size: 24px;
      line-height: 38px;
      color: #fff;
    }
  }
}

.custom-button {
  width: 6px;
  height: 6px;
  background-color: #d0261a;
  border: 5px solid #fff;
  border-radius: 50%;
}

.mini-player {
  position: fixed;
  left: 0px;
  bottom: 0px;
  width: 100%;
  height: 52px;
  background-color: rgba(255, 255, 255, 0.9);
  display: flex;
  z-index: 1;
  .img {
    height: 37px;
    width: 37px;
    margin: 7px 9px 0px 17px;
    background-color: aqua;
    border-radius: 50%;
    img {
      height: 37px;
      width: 37px;
      border-radius: 50%;
    }
    &.play {
      animation: rotate 20s linear infinite;
    }
    &.pause {
      animation-play-state: paused;
    }
  }
  .text {
    flex: 1;
    h2 {
      font-size: 16px;
      line-height: 16px;
      color: #131314;
      margin-top: 12px;
    }
    h3 {
      line-height: 12px;
      font-size: 12px;
      color: #929393;
    }
  }
  .control {
    text-align: center;
    width: 26px;
    height: 26px;
    border-radius: 50%;
    line-height: 26px;
    border: 2px solid #464848;
    margin: 11px 14px 0 0;
    .iconfont {
      color: #464848;
      font-size: 12px;
    }
  }
}

@keyframes rotate {
  0% {
    transform: rotate(0);
  }
  100% {
    transform: rotate(360deg);
  }
}
.minList {
  padding: 15px;
  .btn {
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
    i {
      font-size: 18px;
    }
  }
  ul {
    margin-top: 30px;
    li {
      &.com {
        color: red;
      }
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 15px 0;
      font-weight: 500;
    color: #2E3030;
      .left {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
  }
}
</style>